import DatePicker from './DatePicker/DatePicker';
import Apis from '../../apis/roomPlan';
import {Tooltip, Spin, Modal} from 'antd';
import moment from 'moment';
import {WeaInputSearch, WeaAlertPage, WeaNewScroll} from 'ecCom';
import {WeaTable} from 'comsRedux';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import CreateMeeting from '../createMeeting/index'
import PreviewMeeting from '../previewmeeting/index'

moment.locale('zh-cn');
const WeaTableAction = WeaTable.action;
class RoomPlanContainer extends React.Component {
	constructor(props) {
		super(props);
        this.changeTimeType = this.changeTimeType.bind(this);
        this.timeSelect = this.timeSelect.bind(this);
        this.query = this.query.bind(this);
        this.openCreateMeeting = this.openCreateMeeting.bind(this);
        this.state = {
            timeType: 'day',
            date: new Date(),
            subId: props.subId,
            subName: props.subName,
            color: {},
            baseLoading: true,
            rooms: [],
            useMap: {},//key为roomid，value为使用信息
            startHour: 0,
            endHour: 23,
            duration: 0,
            roomName: '',//搜索栏
            roomLoading: true,
            pageTabKey: '',
            roomId: '',
            createObj: {},
            createVisible: false,
            previewMeetingId:''
        };
	}
	
	componentDidMount() {
        Apis.getRoomReportBaseData().then((result) => {
            let {agreementColor, conflictedColor, usedColor, subname, timestart, timeend, roomConflictType} = result;
            agreementColor || (agreementColor =  "#FFE4C4"), conflictedColor || (conflictedColor = "#FBDFEB"), usedColor || (usedColor = "#E3F6D8");
            this.setState({
                subName: subname,
                color: {agreementColor, conflictedColor, usedColor},
                baseLoading: false,
                startHour: timestart,
                endHour: timeend,
                roomConflictType: roomConflictType
            });
        });
	    this.query();
	}
	
	componentWillReceiveProps(nextProps) {
	    if (nextProps.subId != this.props.subId) {
	        this.setState({
	            subId: nextProps.subId,
                subName: nextProps.subName
            }, this.query);
        }
    }
	
	changeTimeType(timeType) {
	    this.setState({
	        timeType: timeType
        }, this.query);
    }
    
    timeSelect(date, dateRange) {
        this.setState({
            date: date
        }, this.query);
    }
    
    query(value = this.state.roomName, roomId = '') {
        let {timeType} = this.state;
        let params = this.getQueryParams(value);
        this.setState({
            roomName: value,
            roomId: roomId,
            useMap:{}
        });
    
        Apis.getRoomReportData(params).then(
            result => {
                let duration = (timeType == 'day' && result.dspUnit > 0)? 60/result.dspUnit : 0;
                let useMap = {};
                result.datas && result.datas.forEach((obj)=> {
                    if (!obj.roomid) return;
                    useMap[obj.roomid] = obj.info;
                });
                this.setState({
                    rooms: result.rooms || [],
                    useMap: useMap,
                    duration: duration,
                    roomLoading: false
                });
            }
        );
    
        this.queryPageTable(params);
    }
    
    getTableHeaderInfo(timeType,  date, startHour, endHour) {
        let blockNum = 0, tableTitle = '', tableHeaders = [];
        let curmoment = moment.isMoment(date) ? date : moment(date);
        if (timeType == 'day') {
            blockNum = endHour - startHour + 1;
            tableTitle = curmoment.format("M月D日（ddd）单位：时");
            for (startHour; startHour <= endHour; startHour++)
                tableHeaders.push(startHour);
        } else if (timeType == 'week') {
            blockNum = 7;
            tableTitle = curmoment.format("YYYY年ww周");
            for (var i = 0; i < blockNum; i++) {
                tableHeaders.push(curmoment.day(i).format("MM月DD日(ddd)"));
            }
        } else {
            blockNum = curmoment.daysInMonth();
            tableTitle = curmoment.format("YYYY年MM月") + `（${blockNum}天）`;
            for (var i = 0; i < blockNum; i++)
                tableHeaders.push(i);
        }
        return {blockNum: blockNum, tableTitle: tableTitle, tableHeaders: tableHeaders};
    }
    
    getQueryParams(value = this.state.roomName) {
        let {date, subId, timeType} = this.state;
        let curmoment = moment.isMoment(date) ? date : moment(date);
        let params = {
            roomname: value,
            mrtype: '',
            equipment: '',
            currentdate: curmoment.format("YYYY-MM-DD") || '',
            bywhat: timeType == 'day' ? 4 : timeType == 'week' ? 3 : 2,
            curmoment: curmoment
        };
        subId && (params.subid = subId);
        return params;
    }
    
    queryPageTable(params = {}) {
        Apis.getRoomReportList(params).then(
            (result) => {
                this.setState({
                    pageTabKey: result.sessionkey ? result.sessionkey : 'init'
                },() => {
                    this.props.actions.searchPageTable(this.state.pageTabKey);
                });
            }
        );
    }
    queryPageTableByRoomId(roomId) {
        let params = this.getQueryParams();
        params.roomid = roomId;
        this.setState({
            roomId: roomId
        });
        this.queryPageTable(params);
    }
	
	render() {
	    // 上方使用的基础数据
	    let {timeType, baseLoading, subName, color, date, previewMeetingId} = this.state;
        // 列表中使用的数据
        let {roomLoading, startHour, endHour, useMap, rooms, duration, roomId} = this.state;
        // 下方列表的key
        let {pageTabKey} = this.state;
        // 新建会议的控制
        let {createObj, createVisible} = this.state;
        
        let {blockNum, tableTitle, tableHeaders} = this.getTableHeaderInfo(timeType, date, startHour, endHour);
        
		return (
			<div className="wea-meeting-roomplan-con f12">
                <div className="room-plan-top line">
                    {baseLoading ? <div className="align-center"><Spin /></div> :
                        [
                            <span>{subName}</span>,
                            <div className="time-select">
                                {getTimeTypeSpan('day', timeType, this.changeTimeType)}
                                {getTimeTypeSpan('week', timeType, this.changeTimeType)}
                                {getTimeTypeSpan('month', timeType, this.changeTimeType)}
                                <DatePicker type={timeType} className="picker" date={date} onChange={this.timeSelect} ref="picker"/>
                                <span className="icon-Meeting-Refresh" onClick={() => {this.setState({roomLoading: true}, this.query)}}/>
                            </div>,
                            <div className="legend">
                                <div><div className="square" style={{backgroundColor: color.usedColor}}/><span>占用</span></div>
                                <div><div className="square" style={{backgroundColor: color.agreementColor}}/><span>待审批</span></div>
                                <div><div className="square" style={{backgroundColor: color.conflictedColor}}/><span>冲突</span></div>
                            </div>
                        ]
                    }
                </div>
                <WeaNewScroll>
                    <table className="room-plan-tab">
                        <tbody>
                        <tr className="no-border">
                            <th className="first align-center">会议室</th>
                            <th colSpan={blockNum}>{tableTitle || "读取中..."}</th>
                        </tr>
                        {tableHeaders && tableHeaders.length > 0 && (
                            <tr>
                                <th className="search"><WeaInputSearch placeholder="搜索会议室" onSearch={this.query}/></th>
                                {tableHeaders.map((header) => {
                                    return (<th className="room-plan-tab-header">{header}</th>);
                                })}
                            </tr>
                        )}
                        {!roomLoading && (rooms && rooms.length > 0) &&
                            rooms.map((room) => {
                                let tdList = this.createTdList(room, blockNum, this.openCreateMeeting);
                                let title = createRoomTitle(room.title, room.img);
                                let roomTdClass = roomId == room.id ? "room-name cur" : "room-name";
                                return (
                                    <tr>
                                        <Tooltip title={title} getTooltipContainer={() => container}
                                                 overlayClassName="white-tooltip" placement="right">
                                            <td className={roomTdClass} onClick={this.queryPageTableByRoomId.bind(this, room.id)}>{room.name}</td>
                                        </Tooltip>
                                        {tdList}
                                    </tr>
                                );
                            })
                        }
                        </tbody>
                    </table>
                    {roomLoading && <div className="align-center top40"><Spin /></div>}
                    {!roomLoading && (!rooms || rooms.length == 0) && (
                        <WeaAlertPage icon="icon-coms-Journal">
                            <div>暂无会议室</div>
                        </WeaAlertPage>
                    )}
                    {rooms && rooms.length > 0 && <WeaTable sessionkey={pageTabKey} hasOrder={true} onOperatesClick={this.getOperatesClick.bind(this)} getColumns = {this.getColumns} />}
                </WeaNewScroll>
                <CreateMeeting
                    begintime={createObj.startTime}
                    endtime={createObj.endTime}
                    createDate={createObj.createDate || undefined}
                    address={createObj.room}
                    visible={createVisible}//显示true/关闭false
                    onClose={this.closeCreateMeeting}//自定义的关闭组件方式，当点击X、草稿、提交按钮后抛出false,提交后会抛出meetingid
                />
                <PreviewMeeting 
                    meetingId = {previewMeetingId}
                    onClose={(meetingid='')=>{this.setState({previewMeetingId:meetingid})}}
                />
            </div>
		);
	}
	
	closeCreateMeeting = () => {
	    this.query(this.state.roomName, this.state.roomId);
		this.setState({
            createObj: {},
            createVisible: false
        });
	}

    getColumns = (e)=>{
        const {actions} = this.props;
        let newColumns = '';
        newColumns = e.map(column => {
                let newColumn = column;
                newColumn.render = (text, record, index) => { //前端元素转义
                    let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
                    return(
                        newColumn.dataIndex == 'name'  ?
                         <div className="wea-url-name" style ={{cursor:'pointer'}} onClick={()=>{this.setState({previewMeetingId:record.id})}} dangerouslySetInnerHTML={{__html: valueSpan}} />
                        :
                         <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}} />

                    )
                }
                return newColumn;
            });
        return newColumns;
    }
	
	openCreateMeeting(room, startTime, endTime, conflict) {
	    let {date, timeType, duration, roomConflictType} = this.state;
        if (timeType != 'day')
            return;
        if (conflict) {
            if (roomConflictType == 2) {
                Modal.error({content: '该会议室已有会议安排，不能申请会议。'});
                return;
            } else if (roomConflictType == 1) {
                let that = this;
                Modal.confirm({
                    content: '会议起止时间内会议室使用冲突，是否继续申请？',
                    onOk() {
                        that.openCreateMeetingDialog(date, startTime, endTime, room);
                    }
                });
                return;
            }
        }
        this.openCreateMeetingDialog(date, startTime, endTime, room);
	}
    
    openCreateMeetingDialog(date, startTime, endTime, room) {
        let curmoment = moment.isMoment(date) ? date : moment(date);
       
        let createDate = curmoment.format("YYYY-MM-DD");
        let createObj = {
            createDate: createDate,
            startTime: startTime,
            endTime: endTime,
            room: room
        };
        this.setState({
            createObj: createObj,
            createVisible: true
        });
    }
    createTdList = (room, blockNum, onClick) => {
        let {timeType, duration, useMap} = this.state;
        let tooltipContainer = ReactDOM.findDOMNode(this);
        let tdList = [];
        let useArray = useMap[room.id];
        // 创建冲突的、带有提示的td
        let createTooltipTd = function (obj, clickFunc = ()=>{}) {
            let {content, bgcolor, fontcolor, title} = obj;
            let style = {backgroundColor: bgcolor, color: fontcolor || "#000", textAlign: 'center'};
            let td = (
                <Tooltip title={createTitle(title)} getTooltipContainer={() => tooltipContainer}>
                    <td style={style} onClick= {clickFunc(true)} >{content > 1 && content}</td>
                </Tooltip>
            );
            return td;
        };
        if (timeType == 'week' || timeType == 'month') {
            for (let i=0;i<blockNum;i++) {
                tdList.push(<td></td>);
            }
            if (!useArray || useArray.length == 0) {
                return tdList;
            }
            useArray.forEach((obj) => {
                let tdIdx = timeType=='week' ? moment(obj.date).day() : moment(obj.date).date();
                if (tdIdx < 0 || tdIdx >= blockNum) return;
                tdList[tdIdx] = createTooltipTd(obj);
            });
            return tdList;
        }
        
        // 如果是天，逻辑较多
        let {startHour, endHour} = this.state;
        let useBlockMap = {};//形如：小时数:{变色的序号：{背景颜色，字体颜色，内容}，...}
        let subNum = duration == 0 ? 1 : Math.floor(60 / duration);
        // 转换数据格式
        useArray && useArray.forEach((obj) => {
            // 时间处理，确认序号
            if (!obj.time) return;
            let time = obj.time.split(":");
            if (time.length != 2) return;
            let hour = parseInt(time[0]), minute = parseInt(time[1]);
            let idx = duration > 0 ? Math.floor(minute/duration) : 0;
            // 找到该数据对应的存储位置。
            if (!useBlockMap[hour]) useBlockMap[hour] = {};
            let useHour = useBlockMap[hour];
            useHour[idx] = obj;
        });
        
        let createSubTd = (hour, idx) => {
            let startMinute = idx * duration, endMinute = startMinute + duration - 1;
            let startTime = (hour > 9 ? hour : '0' + hour) + ":" + (startMinute > 9 ? startMinute : '0' + startMinute),
                endTime = (hour > 9 ? hour : '0' + hour) + ":" + (endMinute > 9 ? endMinute : '0' + endMinute);
            let clickFunc = (conflict) => {
                return ()=>{onClick(room, startTime, endTime, conflict)};
            };
            // 有值则说明已被占用
            if (useBlockMap[hour] && useBlockMap[hour][idx]) {
                return createTooltipTd(useBlockMap[hour][idx], clickFunc);
            }
            // 空时段
            return (
                <td onClick={clickFunc(false)}></td>
            );
        };
        
        // 生成td列表
        for (startHour; startHour <= endHour; startHour++) {
            let subTdList = [];
            for (let i=0;i<subNum;i++)
                subTdList.push(createSubTd(startHour, i))
            let td = (
                <td>
                    <table className="roomPlan-subTable">
                        <tr>{subTdList}</tr>
                    </table>
                </td>
            );
            tdList.push(td);
        }
        
        return tdList;
    }

    getOperatesClick(record,index,operate,flag){
		let meetingid=record.id;
		let operateType=operate.index;//根据后台接口操作按钮显示顺序确定操作类型 0取消 1提前结束
        if(operateType==0){
            Apis.cancelMeeting({meetingid:meetingid}).then((result)=>{
                this.query();
            });

		}else if(operateType==1){
            Apis.overMeeting({meetingid:meetingid}).then((result)=>{
                this.query();
            });
        }
	}
}

const getTimeTypeSpan = function(timeType, curType, func) {
    let timeTypeLabel;
    switch(timeType) {
        case 'day': timeTypeLabel = '日';break;
        case 'week': timeTypeLabel = '周';break;
        case 'month':timeTypeLabel = '月';break;
        default:timeType = 'month';timeTypeLabel = '月';break;
    }
    return (
        <span className={curType == timeType ? 'cur' : ''} onClick={func.bind(this, timeType)}>{timeTypeLabel}</span>
    );
};
const createRoomTitle = function(titleList, img) {
    let tipArr = [];
    tipArr.push(<div><img src={img || '/images/ecology9/meeting/no_img_wev9.png'} style={{width: 210, height: 140}}/></div>);
    if (Array.isArray(titleList) && titleList.length>0) {
        tipArr = tipArr.concat(titleList.map((tip) => <div>{tip}</div>));
    }
    return <div style={{width: 210}}>{tipArr}</div>;
}

const createTitle = function(titleList) {
    if (Array.isArray(titleList) && titleList.length>0) {
        return (
            <div>
                {titleList.map((meet) => {
                    return (
                        <div>
                        {meet.map((tip) => <div>{tip}</div>)}
                        </div>
                    );
                })}
            </div>
        );
    }
    return undefined;
}

const searchPageTable = (sessionKey) => {
	return (dispatch) => {
		dispatch(WeaTableAction.getDatas(sessionKey));
	}
};


RoomPlanContainer.propTypes = {
    subId: React.PropTypes.string,//分部id
    subName: React.PropTypes.string//分部名称
};

const mapStateToProps = state => {
    const {comsWeaTable} = state;
    return {comsWeaTable}
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators({searchPageTable}, dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps,
    undefined,
    {withRef: true}
)(
    RoomPlanContainer
);
